package vip.xiaonuo.dev.modular.wechat.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import vip.xiaonuo.dev.modular.wechat.controller.DevWechatController;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Map;

/**
 * 企业微信的HTTP请求（httpClient请求方法）
 *
 * @author xsl
 * @date 2024-06-20 16:01
 **/
public class WechatRequest<T> {

    /**
     * get请求（Map入参）
     * @param url
     * @param params
     */
    public static String getMethod(String url, Map<String, String> params) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        try {
            URIBuilder builder = new URIBuilder(url);
            if(params != null){
                for (String key : params.keySet()){
                    builder.addParameter(key, params.get(key));
                }
            }
            URI uri = builder.build();
            // 执行请求
            HttpGet httpGet = new HttpGet(uri);
            response = httpClient.execute(httpGet);
            // 判断相应状态
            if(response.getStatusLine().getStatusCode() == 200) result = EntityUtils.toString(response.getEntity(),"UTF-8");

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                response.close();
                httpClient.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * post 请求（map入参）
     * @param url
     * @param params
     * @return
     */
    public static String postMethod(String url,  Map<String, String> params) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";

        HttpPost httpPost = new HttpPost(url);
        try {
        // 构建请求参数
        StringEntity entity = new StringEntity(params.toString());
        entity.setContentEncoding("utf-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);

        response = httpClient.execute(httpPost);

        if(response.getStatusLine().getStatusCode() == 200) result = EntityUtils.toString(response.getEntity(),"UTF-8");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                response.close();
                httpClient.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return result;
    }


    /**
     * post 请求（javaBean入参）
     * @param url
     * @param req
     * @return
     */
    public String postMethod(String url, T req) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";

        HttpPost httpPost = new HttpPost(url);
        try {
            // 构建请求参数
            String json = JSON.toJSONString(req);
            StringEntity entity = new StringEntity(json);
            entity.setContentEncoding("utf-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            if(response.getStatusLine().getStatusCode() == 200) result = EntityUtils.toString(response.getEntity(),"UTF-8");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                response.close();
                httpClient.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * post 请求（javaBean入参,restTemplate请求）
     * @param url
     * @param req
     * @return
     */
    public String postMethodTemplate(String url, T req) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAcceptCharset(Collections.singletonList(StandardCharsets.UTF_8));
        HttpEntity<T> entity = new HttpEntity<>(req, headers);

        try {
            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
            HttpStatus statusCode = (HttpStatus) response.getStatusCode();
            System.out.println("Status Code: " + statusCode);
            return response.getBody();
           /* if (statusCode.is2xxSuccessful()) {
                System.out.println("消息发送成功");
            } else {
                String errorMessage = response.getBody();
                System.err.println("消息发送失败: " + errorMessage);
            }*/
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
